import { defineStore } from "pinia"
import { ref } from "vue"
import type { Message, Conversation } from "../types"

export const useMessagesStore = defineStore("messages", () => {
  const conversations = ref<Conversation[]>([
    {
      id: "1",
      participants: ["recruiter-1", "candidate-1"],
      lastMessage: {
        id: "1",
        senderId: "system",
        receiverId: "recruiter-1",
        content: "2个牛人可用高效沟通问询",
        type: "system",
        timestamp: "14:45",
        read: false,
      },
      unreadCount: 1,
      jobId: "1",
    },
  ])

  const messages = ref<Message[]>([])

  const getConversationMessages = (conversationId: string) => {
    return messages.value.filter(
      (msg) =>
        conversations.value.find((conv) => conv.id === conversationId)?.participants.includes(msg.senderId) ||
        conversations.value.find((conv) => conv.id === conversationId)?.participants.includes(msg.receiverId),
    )
  }

  const sendMessage = (conversationId: string, content: string, type: "text" | "file" | "interview" = "text") => {
    const newMessage: Message = {
      id: Date.now().toString(),
      senderId: "recruiter-1",
      receiverId: "candidate-1",
      content,
      type,
      timestamp: new Date().toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" }),
      read: false,
    }

    messages.value.push(newMessage)

    // Update conversation last message
    const conversation = conversations.value.find((conv) => conv.id === conversationId)
    if (conversation) {
      conversation.lastMessage = newMessage
    }
  }

  const markAsRead = (conversationId: string) => {
    const conversation = conversations.value.find((conv) => conv.id === conversationId)
    if (conversation) {
      conversation.unreadCount = 0
    }
  }

  return {
    conversations,
    messages,
    getConversationMessages,
    sendMessage,
    markAsRead,
  }
})
